import math
from typing import List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app import crud, schemas
from app.crud.crud_chat import crud_conversation
from app.api import deps
from app.models import User
from app.schemas import (
    MedicalRecordResponse,
    MedicalRecordListResponse,
    MedicalRecordListItem,
    MedicalRecordCountResponse,
    MedicalRecordUpdate,
    MedicalRecordBatchResponse,
    MedicalRecordWithConversations
)
from app.schemas.base import UnifiedResponse, success_response

router = APIRouter()


@router.get("/count", response_model=UnifiedResponse[MedicalRecordCountResponse])
async def get_medical_record_count(
    db: AsyncSession = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_user)
):
    """
    获取当前登录用户的医疗档案数量

    Returns the total count of medical records for the current user
    """
    count = await crud.crud_medical_record.count_by_user(db, user_id=current_user.id)
    return success_response(MedicalRecordCountResponse(count=count))


@router.get("/list", response_model=UnifiedResponse[MedicalRecordListResponse])
async def get_user_medical_records(
    page: int = Query(1, ge=1, description="页码，从1开始"),
    page_size: int = Query(20, ge=1, le=100, description="每页大小，最大100"),
    db: AsyncSession = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_user)
):
    """
    获取当前登录用户的医疗档案列表（分页）

    - **page**: 页码，从1开始
    - **page_size**: 每页大小，默认20，最大100
    """
    records, total = await crud.crud_medical_record.get_user_records_paginated(
        db, user_id=current_user.id, page=page, page_size=page_size
    )

    # 计算总页数
    total_pages = math.ceil(total / page_size) if total > 0 else 0

    # 转换为响应格式
    record_items = []
    for record in records:
        # 获取关联的文件信息
        filename = None
        file_type = None
        file_path = None
        if record.file:
            filename = record.file.filename
            file_type = record.file.file_type
            file_path = record.file.file_path

        record_items.append(MedicalRecordListItem(
            id=record.id,
            file_id=record.file_id,
            disease_name=record.disease_name,
            report_category=record.report_category,
            report_name=record.report_name,
            report_date=record.report_date,
            hospital_name=record.hospital_name,
            extraction_status=record.extraction_status,
            upload_time=record.upload_time,
            created_at=record.created_at,
            filename=filename,
            file_type=file_type,
            file_path=file_path
        ))

    return success_response(MedicalRecordListResponse(
        items=record_items,
        total=total,
        page=page,
        page_size=page_size,
        total_pages=total_pages
    ))


@router.get("/{record_id}", response_model=UnifiedResponse[MedicalRecordBatchResponse])
async def get_medical_record_detail(
    record_id: str,
    db: AsyncSession = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_user)
):
    """
    获取医疗档案详情，返回相同上传时间的所有报告及关联的对话ID

    - **record_id**: 医疗档案ID
    """
    # 先获取指定的医疗档案
    record = await crud.crud_medical_record.get_with_file(db, id=record_id)
    if not record:
        raise HTTPException(status_code=404, detail="Medical record not found")

    # 检查医疗档案是否属于当前用户
    if record.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Access denied")

    # 根据上传时间查询所有相同批次的医疗档案
    batch_records = await crud.crud_medical_record.get_by_upload_time(
        db, user_id=current_user.id, upload_time=record.upload_time
    )

    # 构建响应数据
    records_with_conversations = []
    for batch_record in batch_records:
        # 获取关联的文件信息
        filename = None
        file_type = None
        file_path = None
        if batch_record.file:
            filename = batch_record.file.filename
            file_type = batch_record.file.file_type
            file_path = batch_record.file.file_path

        # 获取文件关联的对话ID
        conversation_ids = []
        if batch_record.file:
            # 通过单独查询获取关联的对话ID
            file_conversations = await crud_conversation.get_conversations_by_file_id(
                db, file_id=batch_record.file_id
            )
            conversation_ids = [str(conv_id) for conv_id in file_conversations]

        records_with_conversations.append(MedicalRecordWithConversations(
            id=batch_record.id,
            file_id=batch_record.file_id,
            disease_name=batch_record.disease_name,
            report_category=batch_record.report_category,
            report_name=batch_record.report_name,
            report_date=batch_record.report_date,
            hospital_name=batch_record.hospital_name,
            extraction_status=batch_record.extraction_status,
            upload_time=batch_record.upload_time,
            created_at=batch_record.created_at,
            filename=filename,
            file_type=file_type,
            file_path=file_path,
            conversation_ids=conversation_ids
        ))

    return success_response(MedicalRecordBatchResponse(
        upload_time=record.upload_time,
        records=records_with_conversations
    ))


@router.put("/{record_id}", response_model=UnifiedResponse[MedicalRecordResponse])
async def update_medical_record(
    record_id: str,
    record_update: MedicalRecordUpdate,
    db: AsyncSession = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_user)
):
    """
    更新医疗档案信息

    - **record_id**: 医疗档案ID
    - **record_update**: 更新的医疗档案数据
    """
    # 获取医疗档案并验证权限
    record = await crud.crud_medical_record.get_with_file(db, id=record_id)
    if not record:
        raise HTTPException(status_code=404, detail="Medical record not found")

    # 检查医疗档案是否属于当前用户
    if record.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Access denied")

    # 更新医疗档案
    updated_record = await crud.crud_medical_record.update(
        db, db_obj=record, obj_in=record_update
    )

    # 获取关联的文件信息
    filename = None
    file_type = None
    file_path = None
    if updated_record.file:
        filename = updated_record.file.filename
        file_type = updated_record.file.file_type
        file_path = updated_record.file.file_path

    return success_response(MedicalRecordResponse(
        id=updated_record.id,
        file_id=updated_record.file_id,
        disease_name=updated_record.disease_name,
        report_category=updated_record.report_category,
        report_name=updated_record.report_name,
        report_date=updated_record.report_date,
        hospital_name=updated_record.hospital_name,
        extraction_status=updated_record.extraction_status,
        upload_time=updated_record.upload_time,
        created_at=updated_record.created_at,
        filename=filename,
        file_type=file_type,
        file_path=file_path
    ))


@router.delete("/{record_id}", response_model=UnifiedResponse[MedicalRecordResponse])
async def delete_medical_record(
    record_id: str,
    db: AsyncSession = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_user)
):
    """
    删除医疗档案

    - **record_id**: 医疗档案ID
    """
    # 获取医疗档案并验证权限
    record = await crud.crud_medical_record.get_with_file(db, id=record_id)
    if not record:
        raise HTTPException(status_code=404, detail="Medical record not found")

    # 检查医疗档案是否属于当前用户
    if record.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Access denied")

    # 获取关联的文件信息（在删除前）
    filename = None
    file_type = None
    file_path = None
    if record.file:
        filename = record.file.filename
        file_type = record.file.file_type
        file_path = record.file.file_path

    # 删除医疗档案
    deleted_record = await crud.crud_medical_record.remove(db, id=record_id)

    return success_response(MedicalRecordResponse(
        id=deleted_record.id,
        file_id=deleted_record.file_id,
        disease_name=deleted_record.disease_name,
        report_category=deleted_record.report_category,
        report_name=deleted_record.report_name,
        report_date=deleted_record.report_date,
        hospital_name=deleted_record.hospital_name,
        extraction_status=deleted_record.extraction_status,
        upload_time=deleted_record.upload_time,
        created_at=deleted_record.created_at,
        filename=filename,
        file_type=file_type,
        file_path=file_path
    ), msg="Medical record deleted successfully")